package com.kjhxtc.restfulrunner;

import cn.hutool.core.lang.Console;

import java.util.Stack;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author 杜神
 * @version 1.0
 * @since 2022/3/16 10:58
 */
public class TaskManager extends Stack<Task> {
    /**
     * 0:固定任务
     * 1:固定时间
     */
    private final int mode;
    private long endMill;
    private long startMill;
    private final AtomicLong countSize=new AtomicLong(0);

    @Override
    public synchronized Task push(Task item) {
        this.countSize.set(super.size()+1);
        return super.push(item);
    }

    public TaskManager() {
        this.mode = 0;
    }

    public TaskManager(long endMill) {
        this.mode = 1;
        this.endMill = endMill;
        this.startMill = System.currentTimeMillis();
    }

    @Override
    public synchronized boolean isEmpty() {
        if (mode == 1) {
            return System.currentTimeMillis() > endMill;
        }
        return super.isEmpty();
    }

    @Override
    public synchronized Task pop() {
        if (mode == 1) {
            if (Log.IS_INFO&&!Log.IS_DEBUG){
                long allMill = this.endMill-this.startMill;
                long costMill = System.currentTimeMillis()-startMill;
                Console.printProgress('▉',60,costMill/(allMill*1.0));
            }
            return super.peek();
        }
        if (Log.IS_INFO&&!Log.IS_DEBUG){
            Console.printProgress('▉',60,(countSize.get()-size()+1)*1.0/countSize.get());
        }
        return super.pop();
    }
}
